// 购物车模块
const state = {
  items: [],
  checkoutStatus: null
}

const getters = {
  cartProducts: (state) => state.items,
  cartTotalPrice: (state) => {
    return state.items.reduce((total, item) => {
      return total + item.price * item.quantity
    }, 0)
  },
  cartItemCount: (state) => state.items.length
}

const mutations = {
  ADD_TO_CART(state, product) {
    const record = state.items.find(item => item.id === product.id)
    if (!record) {
      state.items.push({
        ...product,
        quantity: 1
      })
    } else {
      record.quantity++
    }
  },
  REMOVE_FROM_CART(state, productId) {
    state.items = state.items.filter(item => item.id !== productId)
  },
  SET_CHECKOUT_STATUS(state, status) {
    state.checkoutStatus = status
  },
  EMPTY_CART(state) {
    state.items = []
  }
}

const actions = {
  addToCart({ commit }, product) {
    commit('ADD_TO_CART', product)
  },
  removeFromCart({ commit }, productId) {
    commit('REMOVE_FROM_CART', productId)
  },
  checkout({ commit, state }) {
    // 模拟结账过程
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟随机结账成功或失败
        const success = Math.random() > 0.5
        if (success) {
          commit('EMPTY_CART')
          commit('SET_CHECKOUT_STATUS', 'successful')
          resolve()
        } else {
          commit('SET_CHECKOUT_STATUS', 'failed')
          reject('结账失败')
        }
      }, 1000)
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}